vickcoo

iOS Developer

Swift Structures & Classes:它們之間的差異和相似之處

當您深入研究 Swift 程式設計世界時,您將不可避免地遇到兩個基本概念:structclass。在這篇文章中,我們將揭開它們之間的神秘面紗,使它們更容易理解。

相似之處

  • 定義屬性(Property),包含計算屬性(Computed Property)跟屬性觀察器(Property Observer)
  • 定義方法(Function)
  • 定義下標(Subscript)來提供存取資料的方式
  • 定義建構子(Initializer)
  • 除了Apple提供的方法,還可以進行自訂義擴充(Extension)額外方法
  • 它們都可以遵循Protocols

差異之處

Class有的額外功能,且Structure沒有的

其他不同的地方

語法

這是定義出Structure跟Class最基本的程式碼,後面會繼續為你帶來實際的範例

struct SomeStruct {
}
class SomeClass {
}

Value Type & Reference Type

Swift中的Structure是Value Type,這代表Structure的實例中的屬性,它們在你的程式碼中傳遞時都是會用複製值

struct Person {
    var name: String
    var age: Int
}

let andrew = Person(name: "Andrew", age: 22)
var eric = andrew

eric.age = 41

print(andrew.age) // print: 22
print(eric.age) // print: 41

class是Reference Type,跟structure不同的是當你把class的實例指定給另一個變數,會參照到同一個位址,意思不管修改哪一個實例都是修改同一個,可以參考下面範例

class Person {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

let andrew = Person(name: "Andrew", age: 22)
var eric = andrew

eric.age = 41

print(andrew.age) // print: 41
print(eric.age) // print: 41

建構子 Initializers

在Swift中當你建立structure並且定義了一些屬性,structure會自動產生建構子(Initializer)它有一個專有名詞叫做Memberwise Initializer,但是在class中並沒有這麼方便的功能,還是需要自己手動建立

// struct
struct Person {
    var name: String
    var age: Int
}
let leo = Person(name: "Leo", age: 32)

// class
class Person {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
}
let leo = Person(name: "Leo", age: 32)

使用 Mutating

在structure裡預設你不能修改裡面的屬性,可使用關鍵字mutating來達成修改屬性的目的

可以參考Paul Husdon的這篇文章Mutating methods

struct Person {
    var name: String

    mutating func setName(name: String) {
        self.name = name
    }
}

參考來源